<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>文件下载器</title>
</head>
<body>
  <img id="img" src='' />
  <script type="text/javascript">
    const logProgress = async (res) => {
      const total = res.headers.get('content-length')
      let loaded = 0
      const reader = res.body.getReader()
      const stream = new ReadableStream({
        // 调用构造函数时调用，可以访问数据源，执行初始化操作
        async start(controller) {
          while (true) {
            const { value, done } = await reader.read()
            if (done) {
              console.log('加载完成')
              controller.close()
              return 
            }
            loaded += value.length
            console.log(`Downloaded ${loaded} of ${total} (${(loaded / total * 100).toFixed(2)}%)`)
            controller.enqueue(value)
          }      
        }
      })
      return new Response(stream, { headers: res.headers })
    }
    const readerDownload = async () => {
      const res = await fetch('./oubu.jpeg')
      const logResult = await logProgress(res)
      const blobData = await logResult.blob()
      const url = URL.createObjectURL(blobData)
      const imgElem = document.getElementById('img')
      imgElem.src = url
    }
    readerDownload()
  </script>
</body>
</html>